#
#   api_flickr.py
#
#   David Janes
#   2009.01.13
#
#	Copyright 2008, 2009 David Janes
#
#	Interface to Del.icio.us
#

import os
import sys
import urllib
import types
import pprint
import types

import bm_extract
import bm_uri
import api
import bm_cfg
import bm_work

class Flickr(api.APIReader):
	_convert2work = bm_work.JSON2WORK()

	def CustomizeRestart(self):
		if not self._request_meta.get('api_key'):
			self._request_meta['api_key'] = bm_cfg.cfg.as_string('flickr.api_key')

	def CustomizeAtomItem(self, itemd):
		#
		#	Main image size
		#
		try:
			itemd['link'] = "http://farm%(farm)s.static.flickr.com/%(server)s/%(id)s_%(secret)s.jpg" % itemd
		except KeyError:
			pass

		#
		#	Other image sizes
		#
		for size in [ 'm', 's', 't', 'b', ]:
			try:
				itemd['_size'] = size

				api.add_media(itemd,
					url = "http://farm%(farm)s.static.flickr.com/%(server)s/%(id)s_%(secret)s_%(_size)s.jpg" % itemd,
					medium = "image",
					type = "image/jpeg",
					thumbnail = (size == 't'),
				)
			except KeyError:
				pass

		#
		#	Owner
		#
		try:
			value = itemd.pop('owner')
			if value:
				itemd["author"] = {
					"@" : value,
					"sgn:pk" : "sgn://flickr.com/?pk=" + value,
				}
		except KeyError:
			pass

		#
		#	Remove junk
		#
		for key in [ 'farm', 'secret', 'server', '_size' ]:
			try: del itemd[key]
			except: pass

		api.separate_atom_items(itemd, "flickr:flickr")


		return	api.APIReader.CustomizeAtomItem(self, itemd)

class PhotosSearch(Flickr):
	_uri_base = "http://api.flickr.com/services/rest/?method=flickr.photos.search&format=json"
	_item_path = "photos.photo"

	def __init__(self, **ad):
		Flickr.__init__(self, **ad)

		self.SetRequest(
			user_id = '90594399@N00',
		)

if __name__ == '__main__':
	bm_cfg.cfg.initialize()

	from bm_log import Log
	Log.verbose = True

	api.atom_like = True

	apio = PhotosSearch()
	for item in apio.items:
		pprint.pprint(item)

	## pprint.pprint(apio.meta)
